<template>
  <div>
    <el-row>
      <el-col :span="24" class="addRole">
        <el-button type="primary" @click="dialogFormVisible = true">新增角色</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData" stripe border class="user-table" :height="tableHeight" style="width: 100%;">
      <el-table-column fixed type="index" label="*" sortable min-width="30"></el-table-column>
      <el-table-column prop="role_name" label="角色名称" sortable min-width="180"></el-table-column>
      <el-table-column prop="role_code" label="角色编码" sortable min-width="180"></el-table-column>
      <el-table-column prop="role_desc" label="角色描述" sortable min-width="300"></el-table-column>
      <el-table-column fixed="right" label="操作" align="right" min-width="70">
        <template slot-scope="scope">
          <el-button @click="updateRoles(scope.row)" type="text" size="small">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.currentPage" :page-sizes="[10, 15,20, 25,30,50, 100]" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
  <!-- 角色编辑  -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.isShow" width="900px" top="50px" :close-on-click-modal="false">
      <el-tree :data="tableTreeData" ref="rolesTree" show-checkbox node-key="id"
        :style="{'height':(tableHeight-90)+'px','overflow-y':'auto'}"
        :props="defaultProps" :default-checked-keys='checkedList' :highlight-current="true" @check="checkNode">
        <span class="custom-tree-node" slot-scope="{ node, data }">
            <span :class="!data.edit ? 'tree-name-color' : ''" style="font-size: 15px;font-weight: bold;">{{ node.label }}</span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="isEditBtn" @click="submitDialogList()">确 定</el-button>
      </div>
    </el-dialog>
    <!--新增角色-->
    <el-dialog class="addRoleDialog" title="新增角色" :visible.sync="dialogFormVisible">
      <el-form ref="ruleForm" :model="form" status-icon :rules="rules" class="demo-ruleForm">
        <el-form-item label="名称：" prop="name" :label-width="formLabelWidth">
          <el-input v-model="form.name" type="text" placeholder="请输入名称" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="编码：" prop="code" :label-width="formLabelWidth">
          <el-input v-model="form.code" type="text" placeholder="请输入编码" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述：" prop="describe" :label-width="formLabelWidth">
        <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入内容"
                v-model="form.describe">
        </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="[dialogFormVisible = false]">取 消</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="submitRole('ruleForm')">{{isSubmit ? '提交中...' : '确 定'}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import api from 'plugins/axios/api.js';
import {mapState} from 'vuex'
export default {
  data(){
    let roleName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('内容不能为空'));
      } else {
        if (this.ruleForm.name !== '') {
          this.$refs.ruleForm.validateField('name');
        }
        callback();
      }
    };
    let roleCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('内容不能为空'));
      } else {
        if (this.ruleForm.code !== '') {
          this.$refs.ruleForm.validateField('code');
        }
        callback();
      }
    };
    let roleDescr = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('内容不能为空'));
      } else {
        if (this.ruleForm.describe !== '') {
          this.$refs.ruleForm.validateField('describe');
        }
        callback();
      }
    };
    return {
      rolesData:[],/**角色列表 */
      tableData:[],/**表格列表 */
      dialog:{/**弹框配置 */
        title:'',
        isShow:false
      },
      tableTreeData:[],
      defaultProps:{
        children: 'children',
        label: 'name',
        id: 'id'
      },
      selectRoleId:'',
      checkedList:[],/**选中菜单 */
      pagination:{/**分页参数 */
        currentPage:1,
        pageSize:10,
        total:0
      },
      dialogFormVisible: false,
      isDisabled: false,
      isSubmit:false,
      form: {
        id: '',
        parentId: '',
        name: '',
        code: '',
        describe: '',
        srcType: '1',
      },
      formLabelWidth: '120px',
      ruleForm: {
        name: '',
        code: '',
        describe: ''
      },
      rules: {
        name: [
          { validator: roleName, trigger: 'blur' }
        ],
        code: [
          { validator: roleCode, trigger: 'blur' }
        ],
        describe: [
          { validator: roleDescr, trigger: 'blur' }
        ]
      },
      roleId: '',
      isEditBtn: false
    }
  },
  watch:{
    selectRoleId(newValue,oldValue){
      this.getRoleMenu();
    }
  },
  computed:{
    ...mapState({clientHeight:state=>state.common.clientHeight}),
    tableHeight(){
      return this.clientHeight-184;
    }
  },
  created(){
    this.getRolesData();
    this.getTreeDate();
  },
  methods:{
    getRolesData(){/**获取角色列表 */
      let self = this;
      api.getAllRoles().then(res=>{
        self.rolesData= res.content;
        self.pagination.total =res.content.length;
        this.getTableData();
      })
    },
    getTableData(){/**获取表格列表 */
      this.tableData = this.rolesData.slice((this.pagination.currentPage-1)*this.pagination.pageSize,this.pagination.currentPage*this.pagination.pageSize);
    },
    getTreeDate(){
      let self = this;
      api.menuNodeAll().then(res=>{
        self.tableTreeData = res.content.children;
      })
    },
    updateRoles(row){
      let self = this;
      self.dialog.isShow = true;
      self.dialog.title = '权限编辑';
      self.selectRoleId=row.id;
      self.roleId = row.id;
    },
    getRoleMenu(){
      let self = this;
      self.checkList=[];
      api.getRoleMenu(self.selectRoleId).then(res=>{
        if(res.content&&res.content.length>0){
           res.content.forEach(el=>{
              self.checkList.push(el.id);
          });
        }
        self.$refs.rolesTree.setCheckedKeys( self.checkList);
      })
    },
    handleSizeChange(size){/**切换分页条数 */
      this.pagination.pageSize=size;
      this.pagination.currentPage=1;
      this.getTableData();
    },
    handleCurrentChange(current){/**切换分页页数 */
      this.pagination.currentPage=current;
      this.getTableData();
    },
    checkNode(nodeList,selectList){/**修改菜单选中 */
      let self = this;
      self.checkList=[];
      self.postSelectList=[];
      selectList.checkedNodes.forEach(el => {
        if(el.srcType==2){
          self.postSelectList.push({
            id:null,
            userId:self.selectUserId,
            fileId:el.id,
            parentId:el.parentId
          })
          self.checkList.push(el.id)
        }
      });
    },
    submitDialogList(){
        let _this = this;
        let rolesTree = this.$refs.rolesTree;
        let arr = rolesTree.getHalfCheckedKeys().concat(rolesTree.getCheckedKeys());
        let menuIds = arr.join(',');
        let params = new URLSearchParams();
        params.append("menuIds", menuIds);
        _this.isEditBtn = true;
        api.roleEdit(params,_this.roleId).then( (res) => {
          if (res.statusCode === '200') {
            _this.$message({
              message: '上传成功！',
              type: 'success',
              duration: 1500,
              onClose:function () {
                _this.isEditBtn = false;
                _this.getRolesData();
                _this.$set(_this.dialog,'isShow',false)
              }
            })
          } else {
            _this.$message.error(res.data.desc);
          }
        }).catch((catchres) => {
          _this.$message.error("上传编辑失败！请重新提交");
        })
    },
    submitRole(formName) {
      let _this = this;
      if(this.name === '' || this.role === '' || this.describe === ''){
        this.dialogFormVisible = false
      }else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let dataObj = {};
            dataObj.role_name = _this.form['name'];
            dataObj.role_code = _this.form['code'];
            dataObj.role_desc = _this.form['describe'];
            let dataRole = JSON.stringify(dataObj);
            let localAdd = JSON.parse(dataRole);
            localAdd.id = _this.tableData.length + 1;
            _this.isDisabled = true;
            _this.isSubmit = true;
             api.addRole(dataObj).then(
                 res => {
                   console.log(res.statusCode)
                   if(res.statusCode === '200'){
                     _this.$message({
                       message: '增员成功！',
                       type: 'success',
                       duration: 1500,
                       onClose:function () {
                         _this.isDisabled = false;
                         _this.isSubmit = false;
                         _this.dialogFormVisible = false;
                         if (_this.tableData.length < 10) {
                           _this.tableData.push(localAdd);
                         }
                       }
                     })
                   }
                 },
                 err => {
                   // console.log(err);
                   _this.$message.error({
                     message: '提交失败，请重新提交',
                     showClose: true,
                     duration: 2000,
                     onClose: function () {
                       _this.isDisabled = false;
                       _this.isSubmit = false;
                     }
                   });
                 }
             )
          } else {
            return false;
          }
        });
      }
    }
  }
}
</script>
<style lang="stylus" scoped>
  .addRole
    padding-bottom 10px
  .addRoleDialog /deep/
    .el-dialog
      min-width 400px!important
</style>

